package com.ruoyi.synchdata;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.course.domain.LabCourse;
import com.ruoyi.course.domain.LabCourseTeacher;
import com.ruoyi.course.mapper.LabCourseMapper;
import com.ruoyi.course.mapper.LabCourseTeacherMapper;
import com.ruoyi.course.service.ILabCourseService;
import com.ruoyi.labdata.domain.LabOrgnization;
import com.ruoyi.labdata.service.ILabOrgnizationService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;

@Component("synchTask")
public class SynchDataServiceImpl {
	@Autowired
	private ILabOrgnizationService labOrgnizationService;
	@Autowired
	private ISysUserService userService;
	@Autowired
	private SysUserMapper userMapper;
	@Autowired
	private ISysDictDataService sysDictDataService;
	@Autowired
	private LabCourseMapper labCourseMapper;
	@Autowired
	private LabCourseTeacherMapper labCourseTeacherMapper;
	@Autowired
	private ISysConfigService configService;
	
	private static final Logger log = LoggerFactory.getLogger(SynchDataServiceImpl.class);
	
	public int synchDept(){
		int pageNum = 1;
		int pageSize = 300;
		Map<String, LabOrgnization> allMap = new HashMap<String, LabOrgnization>();
		Map<String, LabOrgnization> orgMap = SynchDataForNY.synchDepartmentData(pageNum,pageSize);
		allMap.putAll(orgMap);
		while(orgMap.size()==pageSize){
			pageNum++;
			orgMap = SynchDataForNY.synchDepartmentData(pageNum,pageSize);
			allMap.putAll(orgMap);
		}
		List<LabOrgnization> databaseOrgList =  labOrgnizationService.selectLabOrgnizationList(new LabOrgnization());
		for(LabOrgnization itemOrg : databaseOrgList){
			LabOrgnization synchOrg = allMap.get(itemOrg.getOrgCode());
			if(synchOrg!=null){
				synchOrg.setOrgId(itemOrg.getOrgId());
				synchOrg.setParentId(itemOrg.getParentId());
			}
		}
		for(LabOrgnization synchOrg : allMap.values()){
			if(synchOrg.getOrgId()!=null){
				continue;
			}
			List<LabOrgnization> linkParent = new ArrayList<LabOrgnization>();
			linkParent.add(synchOrg);
			//上级代码
			String parentCode = synchOrg.getParentName();
			while(parentCode!=null && allMap.get(parentCode)!=null){
				LabOrgnization parent = allMap.get(parentCode);
				if(parent!=null){
					linkParent.add(parent);
					parentCode = parent.getParentName();
				}
			}
			for(int i=linkParent.size() -1 ; i>=0; i--){
				LabOrgnization parent = linkParent.get(i);
				if(parent.getOrgId()!=null){
					continue;
				}
				if(StringUtils.isEmpty(parent.getParentName().trim())){
					parent.setParentId(Long.valueOf(1));
				}else if(i<linkParent.size() -1){
					parent.setParentId(linkParent.get(i+1).getOrgId());
				}
				parent.setOrgGroupOpt(Long.valueOf(1));
				parent.setHasChildOpt(Long.valueOf(1));
				parent.setOrgFunctionOpt(Long.valueOf(1));
				parent.setCreateBy("admin");
				parent.setCreateYear("2000");
				try{
					labOrgnizationService.insertLabOrgnization(parent);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		return allMap.size();
	}
	
	public int synchUser(){
		String initPassword = SecurityUtils.encryptPassword(configService.selectConfigByKey("sys.user.initPassword"));
		List<LabOrgnization> databaseOrgList =  labOrgnizationService.selectLabOrgnizationList(new LabOrgnization());
		Map<String, LabOrgnization> orgMap = new HashMap<String, LabOrgnization>();
		for(LabOrgnization itemOrg : databaseOrgList){
			orgMap.put(itemOrg.getOrgCode(),itemOrg);
		}
		Long[] roleIds = new Long[1];
		roleIds[0] = Long.valueOf(2);
		int pageNum = 1;
		int pageSize = 300;
		List<SysUser> synchUserList = SynchDataForNY.synchUserData(pageNum, pageSize);
		int count = synchUserList.size();
		saveSynchUser(initPassword, orgMap, roleIds, synchUserList);
		while(synchUserList.size()==pageSize){
			pageNum++;
			 synchUserList = SynchDataForNY.synchUserData(pageNum, pageSize);
			 count += synchUserList.size();
			 saveSynchUser(initPassword, orgMap, roleIds, synchUserList);
		}
		return count;
	}

	private void saveSynchUser(String initPassword, Map<String, LabOrgnization> orgMap, Long[] roleIds,
			List<SysUser> synchUserList) {
		String[] userNames = new String[synchUserList.size()];
		int i=0;
		for(SysUser synchUser : synchUserList){
			userNames[i] = synchUser.getUserName();
			i++;
		}
		List<SysUser> databaseUserList = userService.selectUserByNames(userNames);
		Map<String, SysUser> userMap = new HashMap<String, SysUser>();
		for(SysUser databaseUser : databaseUserList){
			userMap.put(databaseUser.getUserName(), databaseUser);
		}
		
		//角色编号为2
		for(SysUser synchUser : synchUserList){
			if(userMap.get(synchUser.getUserName())!=null){
				SysUser databaseUser = userMap.get(synchUser.getUserName());
				databaseUser.setBh(synchUser.getBh());
				databaseUser.setSfzx(synchUser.getSfzx());
				databaseUser.setZy(synchUser.getZy());
				databaseUser.setZydm(synchUser.getZydm());
				databaseUser.setXznj(synchUser.getXznj());
				databaseUser.setYx(synchUser.getYx());
				databaseUser.setYxdm(synchUser.getYxdm());
				databaseUser.setSflb(synchUser.getSflb());
				userMapper.updateUser(databaseUser);
			}else{
				synchUser.setRoleIds(roleIds);
				if(orgMap.get(synchUser.getYxdm())!=null){
					synchUser.setDeptId(orgMap.get(synchUser.getYxdm()).getOrgId());
				}
				synchUser.setPassword(initPassword);
				userService.insertUser(synchUser);
			}
		}
	}
	
	public int synchBKCourse(Long timetableId, String xn, Integer xq,Map<String, LabOrgnization> orgMap){
		
		int pageNum = 1;
		int pageSize = 200;
		List<LabCourse> allBkCourseList = new ArrayList<LabCourse>();
		List<LabCourse> courseList = SynchDataForNY.synchBkCourseData(pageNum, pageSize,xn,xq);
		allBkCourseList.addAll(courseList);
		int count = courseList.size();
		while(count==pageSize){
			pageNum++;
			List<LabCourse> courseList1 = SynchDataForNY.synchBkCourseData(pageNum, pageSize,xn,xq);
			count = courseList1.size(); 
			allBkCourseList.addAll(courseList1);
		}
		//保存所有字典数据
		Map<String, SysDictData> majorDictMap = new HashMap<String, SysDictData>();
		SysDictData queryDictData = new SysDictData();
		queryDictData.setDictType("majorOpt");
		List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(queryDictData);
		sysDictDataList.forEach(item -> {
			majorDictMap.put(item.getDictValue(), item);
		});
		//保存所有课程数据
		for(int i=0;i<allBkCourseList.size();i++){
			LabCourse item = allBkCourseList.get(i);
			if(StringUtils.isEmpty(item.getCollegeOrgName())){
				continue;
			}
			item.setTimetableId(timetableId);
			LabOrgnization org = orgMap.get(item.getCollegeOrgName());
			if(org==null){
				log.warn("教师课程表中的学院名称:"+item.getCollegeOrgName()+" 不存在");
				continue;
			}
			item.setCollegeOrgId(org.getOrgId());
			if(majorDictMap.get(item.getMajorOpt())==null){
				//保存专业数据
				SysDictData dictData = new SysDictData();
				dictData.setDictType("majorOpt");
				dictData.setCreateBy("admin");
				dictData.setCreateTime(DateUtils.getNowDate());
				dictData.setDictLabel(item.getMajorName());
				dictData.setDictValue(item.getMajorOpt());
				dictData.setDictSort(Long.valueOf("0"));
				dictData.setIsDefault("N");
				sysDictDataService.insertDictData(dictData);
				majorDictMap.put(item.getMajorOpt(), dictData);
			}
			labCourseMapper.insertLabCourse(item);
			List<LabCourseTeacher> courseTeacherList = item.getCourseTeacherList();
			for (LabCourseTeacher labCourseTeacher : courseTeacherList) {
				labCourseTeacher.setCourseId(item.getCourseId());
				labCourseTeacherMapper.insertLabCourseTeacher(labCourseTeacher);
			}
			
		}
		return count;
	}
	
	public int synchYJSCourse(Long timetableId, String xn, Integer xq,Map<String, LabOrgnization> orgMap){
		String xqName = "第一学期";
		if(xq==2){
			xqName = "第二学习";
		}
		String xn1 = xn.split("-")[0]; 
		int pageNum = 1;
		int pageSize = 200;
		List<LabCourse> allBkCourseList = new ArrayList<LabCourse>();
		List<LabCourse> courseList = SynchDataForNY.synchYJSCourseData(pageNum, pageSize,xn1,xqName);
		allBkCourseList.addAll(courseList);
		int count = courseList.size();
		while(count==pageSize){
			pageNum++;
			List<LabCourse> courseList1 = SynchDataForNY.synchBkCourseData(pageNum, pageSize,xn1,xq);
			count = courseList1.size(); 
			allBkCourseList.addAll(courseList1);
		}
		//保存所有课程数据
		for(int i=0;i<allBkCourseList.size();i++){
			LabCourse item = allBkCourseList.get(i);
			if(StringUtils.isEmpty(item.getCollegeOrgName())){
				continue;
			}
			item.setTimetableId(timetableId);
			LabOrgnization org = orgMap.get(item.getCollegeOrgName());
			if(org==null){
				log.warn("教师课程表中的学院名称:"+item.getCollegeOrgName()+" 不存在");
				continue;
			}
			item.setCollegeOrgId(org.getOrgId());
			labCourseMapper.insertLabCourse(item);
			List<LabCourseTeacher> courseTeacherList = item.getCourseTeacherList();
			for (LabCourseTeacher labCourseTeacher : courseTeacherList) {
				labCourseTeacher.setCourseId(item.getCourseId());
				labCourseTeacherMapper.insertLabCourseTeacher(labCourseTeacher);
			}
		}
		return count;
	}
	
	public static void main(String args[]){
		//SynchDataServiceImpl service = new SynchDataServiceImpl();
		//service.synchYJSCourse();
		System.out.println("001100000000".lastIndexOf("1"));
	}
	
}
